from selenium import webdriver
from selenium.common import TimeoutException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 配置Selenium
chrome_options = Options()
chrome_options.add_argument("--headless")  # 无头模式
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
chrome_options.add_argument("--blink-settings=imagesEnabled=false")
chrome_options.add_experimental_option("prefs", {
    "profile.managed_default_content_settings.images": 2,
    "profile.managed_default_content_settings.javascript": 1,  # 保留JS（动态内容可能需要）
})

# chrome_options.page_load_strategy = 'eager'
# 指定Chrome驱动路径
service = Service('./chromedriver.exe')  # 替换为你的chromedriver路径

driver = webdriver.Chrome(service=service, options=chrome_options)
driver.set_page_load_timeout(10)  # 30秒后超时
page_source = None
try:
    # # https://quote.eastmoney.com/qihuo/ps2508.html
    url = "https://gushitong.baidu.com/futures/ab-JM2508"
    driver.get(url)
    WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "b_price stock-color-stock-color-red")))
    print("页面加载完成")
    page_source = driver.page_source
except TimeoutException:
    print("页面加载超时，尝试继续获取源码")
    page_source = driver.page_source
finally:
    driver.quit()
soup = BeautifulSoup(page_source, 'html.parser')
# # 示例：提取页面标题
# title = soup.text
# print("页面标题:", title)

with open("./fetch/app_baidu.html", "w", encoding="utf-8") as file:
    file.write(str(soup))  # 或 file.write(soup.prettify())

print("HTML 已保存到 app.html")
#
# # 查找class为"price"的span标签
# price_span = soup.find('span', class_='price')
#
# if price_span:
#     # 获取文本内容并转换为浮点数
#     price = float(price_span.text)
#     print(price)  # 输出: 1311.0
#     # 如果需要保留两位小数
#     print("{:.2f}".format(price))  # 输出: 1311.00
# else:
#     print("未找到价格信息")


